<template>
    <el-drawer v-model="diagVisible" title="方案拆解" :size="1052" @closed="close" @open="open">
        <div class="tips">
            <img src="../../../../assets/jingshi.png" alt="" />
            注意：方案拆解可能会导致已选点位减少
        </div>
        <div class="info">
            <div>
                方案名称：<span>{{ row.planName }}</span>
            </div>
            <div>
                投放周期：<span>{{ row.putInPeriod }}</span>
            </div>
            <div>
                投放时长：<span>{{ row.secondsName }}</span>
            </div>
            <div>
                投放频次：<span>{{ row.numbersName }}</span>
            </div>
            <div>
                已选点位数：<span>{{ row.selectedPointNum }}</span>
            </div>
        </div>
        <div>
            <el-tabs v-model="activeName" size="small" @tab-click="handleClick">
                <el-tab-pane label="按周期拆解" name="1">
                    <div class="tab-header publish-date">
                        <el-date-picker v-model="time" class="publish-date" type="date" placeholder="选择日期"
                            format="YYYY/MM/DD" value-format="YYYY-MM-DD" :disabled-date="disabledDate" />
                        <div class="btns">
                            <el-button type="primary" :disabled="!time" @click="join">加入列表</el-button>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane v-if="!(row.planStatus === '003')" label="按时长拆解" name="3">
                    <div class="tab-header">
                        <XcForm ref="xcFormRef" class="pinmei-form" :form-data="formData" :columns="formColumns">
                            <template #select-prefix> 选择时长 </template>
                        </XcForm>
                        <div class="btns">
                            <el-button type="primary" :disabled="!formData.select" @click="join">加入列表</el-button>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane v-if="!(row.planStatus === '003')" label="按频次拆解" name="4">
                    <div class="tab-header">
                        <el-form ref="xcFormRef" class="pinmei-form">
                            <el-form-item prop="numbers">
                                <el-select v-model="formData.numbers" placeholder="请选择" class="select">
                                    <template #prefix>
                                        <div class="label">选择频次</div>
                                    </template>

                                    <el-option v-for="(item, key) in numbersType" :key="key" :label="item" :value="key" />
                                </el-select>
                            </el-form-item>
                        </el-form>
                        <div class="btns">
                            <el-button type="primary" :disabled="!formData.numbers" @click="join">加入列表</el-button>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane v-if="!(row.planStatus === '003')" label="按点位拆解" name="2">
                    <div class="tab-header">
                        <div class="btns">
                            <el-button type="primary" @click="join">添加方案</el-button>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
            <XcTable id="xc-table" :data="tableData" :height="maxTableHeight" :columns="tableColumns">
                <template #name="scope">
                    <el-input v-model="scope.row.name" :disabled="scope.row.disabled"
                        @input="scope.row.planName = scope.row.name" />
                </template>
                <template #compactNum="scope">
                    <el-input v-if="+activeName === 2" v-model="scope.row.compactNum" type="number" />
                    <template v-else>
                        {{ scope.row.compactNum }}
                    </template>
                </template>
                <template #regulateNum="scope">
                    <el-input v-if="+activeName === 2" v-model="scope.row.regulateNum" type="number" />
                    <template v-else>
                        {{ scope.row.regulateNum }}
                    </template>
                </template>
                <template #action="scope">
                    <el-button type="text" @click="onDelData(scope.$index, scope.row)">删除</el-button>
                </template>
            </XcTable>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="diagVisible = false">取 消</el-button>
                <el-button type="primary" :loading="loading" :disabled="!tableData.length" @click="disassembly">
                    开始拆解
                </el-button>
            </span>
        </template>
    </el-drawer>
</template>

<script lang="ts" setup>
import { ref, defineExpose, reactive, Ref, computed } from 'vue';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/XcTable.vue';
import XcForm from '@x-tech/fe-pc-components/src/components/XcForm/index.vue';
import { ElNotification, ElMessage } from 'element-plus';
import { durationType, numbersType } from '@/utils/config.ts';
import { planDisassemble } from '@/api/plan.ts';
import useTableSetting from '@/hooks/useTableSetting.ts';
import { Edit } from '@element-plus/icons';
import { el } from 'element-plus/lib/locale/index';
import { Console } from 'console';

interface op {
    value: string | number;
    label: string;
}
const props = defineProps({
    row: {
        type: Object,
        default() {
            return {};
        },
    },
});

const emit = defineEmits(['getList']);
const tableColumns = [
    { label: '方案名称', key: 'name', render: true, prop: { width: '220', fixed: 'left' } },
    { label: '投放时长', key: 'secondsName', prop: { width: '120' } },
    { label: '投放频次', key: 'numbersName', prop: { width: '150' } },
    { label: '签约点位', key: 'compactNum', render: true, prop: { width: '150' } },
    { label: '调剂点位', key: 'regulateNum', render: true, prop: { width: '150' } },
    { label: '投放周期', key: 'putInPeriod', prop: { width: '230' } },
    { label: '操作', key: 'action', render: true, prop: { width: '100' } },
];

let tableData = ref([]);
let loading = ref(false);
let diagVisible = ref(false);
let time = ref('');
let activeName = ref('1');
let copyVal = ref('');
let allTime = reactive([]);
let options: Ref<op[]> = ref([]);
const formData = reactive({
    select: '',
    numbers: '',
});
let formColumns = computed(() => {
    let arr = [];
    let durationTypeOp = [];
    for (let key in durationType) {
        durationTypeOp.push({
            label: durationType[key],
            value: key,
        });
    }
    arr.push({
        label: '',
        prop: 'select',
        type: 'select',
        attr: {
            filterable: true,
            clearable: true,
            placeholder: '请选择',
        },
        slotName: 'prefix',
        options: durationTypeOp,
    });
    return arr;
});

const { maxTableHeight } = useTableSetting();

const getDate = (n: number | string): string | number => {
    let now = new Date(n),
        y = now.getFullYear(),
        m = now.getMonth() + 1,
        d = now.getDate();
    return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
};
const handleShowPopover = (scope: any) => {
    copyVal.value = scope.row.name;
};
const disabledDate = (date: any) => {
    let rang = props.row.putInPeriod.split('~');
    let week = new Date(date).getDay();
    let nowDate = new Date().getTime();
    let startDate = new Date(rang[0]).getTime();
    let endDate = new Date(rang[1]).getTime();
    let eachDate = new Date(date).getTime();
    // let lastDayWeek = new Date(endDate).getDay();
    let disabled = false;
    // 禁用时间取当前时间和方案开始时间交集
    if (nowDate >= startDate) {
        disabled = eachDate <= nowDate || eachDate > endDate || week !== 6;
    } else {
        disabled = eachDate <= startDate || eachDate > endDate || week !== 6;
    }
    // let disabled = new Date(date) <= new Date(rang[0]) || new Date(date) >= new Date(rang[1]) || week !== 6;
    for (let i = 0; i < tableData.value.length; i++) {
        let cur = tableData.value[i] as any;
        let curDate = cur.putInPeriod.split('~')[0];
        disabled = disabled || getDate(eachDate) === getDate(new Date(curDate).getTime());
        if (disabled) {
            break;
        }
    }
    return disabled;
};
const setOption = () => {
    for (let i = 1; i < 36; i++) {
        let obj = {
            label: i * 5 + 's',
            value: '00' + i,
        };
        options.value.push(obj as never);
    }
};
const handleClick = () => {
    let arr = props.row.putInPeriod.split('~');
    allTime = arr.map((item: any) => {
        return getDate(new Date(item).getTime());
    });
    formData.select = '';
    formData.numbers = '';
    tableData.value = [];
};
const isDisabled = (i: number) => {
    return props.row.planStatus === '003' && !i && props.row.beginTime < new Date().getTime();
};

const renderTable = () => {
    tableData.value = [];



    let length = allTime.length / 2;
    for (let i = 0; i < length; i++) {
        let obj = {
            planName:
                props.row.planStatus === '003' && props.row.beginTime < new Date().getTime()
                    ? `${props.row.planName}${!i ? '' : i}`
                    : `${props.row.planName}${i + 1}`,
            disabled: isDisabled(i),
            name:
                props.row.planStatus === '003' && props.row.beginTime < new Date().getTime()
                    ? `${props.row.planName}${!i ? '' : i}`
                    : `${props.row.planName}${i + 1}`,
            secondsName: props.row.secondsName,
            numbersName: props.row.numbersName,
            compactNum: props.row.compactNum,
            regulateNum: props.row.regulateNum,
            putInPeriod: allTime[i * 2] + '~' + allTime[i * 2 + 1],
            beginDate: allTime[i * 2],
            endDate: allTime[i * 2 + 1],
            isShow: false,
        };
        tableData.value.push(obj as never);
    }
}

const byCycle = () => {
    if (!time.value) {
        ElNotification({
            title: '提示信息',
            message: '请先选择时间',
            type: 'warning',
        });
        return;
    }

    let nextDate = new Date(time.value).getTime() - 60 * 60 * 24 * 1000;
    nextDate = getDate(nextDate) as number;
    allTime.push(time.value as never, nextDate as never);
    allTime = allTime.sort((a, b) => {
        return new Date(a).getTime() - new Date(b).getTime();
    });
  
    renderTable();
    time.value = '';
};
const byTimes = () => {
    if (!formData.select) {
        ElNotification({
            title: '提示信息',
            message: '请先选择时长',
            type: 'warning',
        });
        return;
    }
    let time = 0;
    tableData.value.forEach((item: any) => {
        time += parseInt(item.secondsName, 10);
    });
    if (
        // eslint-disable-next-line operator-linebreak
        time + parseInt(durationType[formData.select], 10) >
        parseInt(props.row.secondsName, 10)
        // parseInt(durationType[formData.select], 10) > parseInt(props.row.secondsName, 10)
    ) {
        ElNotification({
            title: '提示信息',
            message: '加入失败，总时长超过原方案',
            type: 'warning',
        });
        return;
    }
    let obj = {
        planName: props.row.planName + (tableData.value.length + 1),
        name: props.row.planName + (tableData.value.length + 1),
        secondsName: durationType[formData.select],
        seconds: formData.select,
        numbersName: props.row.numbersName,
        compactNum: props.row.compactNum,
        regulateNum: props.row.regulateNum,
        putInPeriod: props.row.putInPeriod,
        beginDate: props.row.putInPeriod.split('~')[0],
        endDate: props.row.putInPeriod.split('~')[1],
        isShow: false,
    };
    tableData.value.push(obj as never);
    formData.select = '';
};
const byRate = () => {
    if (!formData.numbers) {
        ElNotification({
            title: '提示信息',
            message: '请先选选择频次',
            type: 'warning',
        });
        return;
    }
    const rateNum = tableData.value.reduce((pre: number, cur: any) => {
        return pre + parseInt(cur.numbersName, 10);
    }, 0);
    if (rateNum + parseInt(numbersType[formData.numbers], 10) > parseInt(props.row.numbersName, 10)) {
        ElNotification({
            title: '提示信息',
            message: '加入失败，总频次超过原方案',
            type: 'warning',
        });
        return;
    }
    let obj = {
        planName: props.row.planName + (tableData.value.length + 1),
        name: props.row.planName + (tableData.value.length + 1),
        secondsName: props.row.secondsName,
        numbersName: numbersType[formData.numbers],
        numbers: formData.numbers,
        compactNum: props.row.compactNum,
        regulateNum: props.row.regulateNum,
        putInPeriod: props.row.putInPeriod,
        beginDate: props.row.putInPeriod.split('~')[0],
        endDate: props.row.putInPeriod.split('~')[1],
        isShow: false,
    };
    tableData.value.push(obj as never);
    formData.numbers = '';
};
const byPoint = () => {
    const pointNum = tableData.value.reduce((pre: number, cur: any) => {
        return pre + +cur.regulateNum + +cur.compactNum;
    }, 0);
    if (pointNum > +props.row.selectedPointNum) {
        ElNotification({
            title: '提示信息',
            message: '加入失败，签约点位数与调剂点位数之和超过原方案的已选点位数',
            type: 'warning',
        });
        return;
    }
    let obj = {
        planName: props.row.planName + (tableData.value.length + 1),
        name: props.row.planName + (tableData.value.length + 1),
        secondsName: props.row.secondsName,
        numbersName: props.row.numbersName,
        compactNum: 0,
        regulateNum: 0,
        putInPeriod: props.row.putInPeriod,
        beginDate: props.row.putInPeriod.split('~')[0],
        endDate: props.row.putInPeriod.split('~')[1],
        isShow: false,
    };
    tableData.value.push(obj as never);
};
const onDelData = (index: number, row: any) => {
    if (index === 0 && tableData.value.length === 1) {
        allTime.splice(index, 2);
        tableData.value=[]
        let arr = props.row.putInPeriod.split('~');
        allTime = arr.map((item: any) => {
            return getDate(new Date(item).getTime());
        });
    } else if (index === 0) {
        allTime.splice(index + 1, 2);
        renderTable();
    } else {
        allTime.splice(2 * index - 1, 2);
        renderTable();
    }
    // console.log(row, allTime);
    // return false;
    // tableData.value.splice(index, 1);
};
const join = () => {
    if (+activeName.value === 1) {
        byCycle();
    } else if (+activeName.value === 3) {
        byTimes();
    } else if (+activeName.value === 4) {
        byRate();
    } else if (+activeName.value === 2) {
        byPoint();
    }
};
const disassembly = async () => {
    let flag = false;
    tableData.value.forEach((item: any) => {
        if (!item.name) {
            flag = true;
        }
    });
    if (flag) {
        ElNotification({
            title: '提示信息',
            message: '方案名称不能为空',
            type: 'warning',
        });
    }

    if (+activeName.value === 3) {
        let time = 0;
        tableData.value.forEach((item: any) => {
            time += parseInt(item.secondsName, 10);
        });
        if (time < parseInt(props.row.secondsName, 10)) {
            ElNotification({
                title: '提示信息',
                message: '总时长小于原方案，无法拆解',
                type: 'warning',
            });
            return;
        }
    }
    if (+activeName.value === 2) {
        let reg = /^([0]|[1-9][0-9]*)$/;
        let isTrue = tableData.value.find((item: any) => !reg.test(item.compactNum) || !reg.test(item.regulateNum));
        if (isTrue) {
            ElNotification({
                title: '提示信息',
                message: '签约点位数，调剂点位数必须为正整数',
                type: 'warning',
            });
            return;
        }
    }
    loading.value = true;
    const data = await planDisassemble({
        planId: props.row.planId,
        planList: tableData.value,
        type: +activeName.value,
    }).catch((err: any) => {
        console.log(err);
        loading.value = false;
    });
    if (data) {
        diagVisible.value = false;
        loading.value = false;
        ElMessage.success('操作成功');
        emit('getList');
    }
};

const show = () => {
    diagVisible.value = true;
    if (!options.value.length) {
        setOption();
    }
};
const close = () => {
    allTime = [];
    tableData.value = [];
};
const open = () => {
    // allTime = props.row.putInPeriod.split('~');
    let arr = props.row.putInPeriod.split('~');
    allTime = arr.map((item: any) => {
        return getDate(new Date(item).getTime());
    });

    loading.value = false;
    activeName.value = '1';
    formData.select = '';
};
defineExpose({
    show,
});
</script>

<style lang="scss" scoped>
.tips {
    display: flex;
    height: 40px;
    align-items: center;
    background: #fff7e8;
    border-radius: 4px;
    font-size: 14px;
    color: #666666;
    padding: 0 20px;
    margin-bottom: 25px;

    img {
        width: 18px;
        height: 18px;
        margin-right: 10px;
    }
}

.info {
    display: flex;
    flex-wrap: wrap;
    background: #f5f5f5;
    border-radius: 4px;
    padding: 14px 16px;
    box-sizing: border-box;
    margin-bottom: 24px;
    line-height: 26px;

    >div {
        width: 33%;
        color: rgba(153, 153, 153, 1);
        font-size: 14px;

        span {
            color: #333;
        }
    }
}

.tab-header {
    display: flex;
    margin-bottom: 25px;
}

.btns {
    margin-left: 20px;
}

::v-deep.el-dialog .el-dialog__footer {
    padding: 10px 20px !important;
}

::v-deep.publish-date {
    .el-date-editor.el-input {
        width: 280px;
    }

    .el-input__prefix .el-input__icon {
        display: none;
    }

    .el-range__icon {
        position: absolute;
        left: 7px;
    }

    .el-input__prefix-inner {
        &::before {
            content: '选择日期';
            padding-right: 15px;
            font-size: 14px;
            color: #999;
        }
    }

    &.in-time {
        .el-range__icon {
            margin-right: -8px;
            width: 80px;
            font-style: inherit;

            svg {
                display: none;
            }

            &::before {
                content: '交房时间';
                padding-right: 15px;
                font-size: 14px;
                color: #999;
            }
        }

        .el-range__close-icon {
            vertical-align: middle;
            right: -10px;
            top: -2px;
        }
    }

    .el-input__inner {
        padding-left: 82px;
    }
}

::v-deep.pinmei-form {
    .columns {
        height: 36px;
        width: 280px !important;
        overflow: hidden;
    }

    .el-form-item .el-input__inner {
        padding-left: 80px !important;
    }
}

::v-deep .el-tabs__nav-wrap::after {
    height: 1px;
}

.edit {
    width: 12px;
    height: 12px;
    position: relative;
    top: 2px;
    cursor: pointer;
}
</style>
